import fetch  from 'isomorphic-fetch'
import config from '@/config'
import router from '@/router'
import fetchJsonp from 'fetch-jsonp'
import iView                 from 'iview'

function parseJSON(response) {
    return response.json();
}

function parseFormData(data){
    let f = new FormData();
    for(let k in data){
        data[k]!== undefined&&data[k]!== null&&f.append(k,data[k]);
    }
    return f;
}

function checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response;
    }
    const error = new Error(response.statusText);
    error.response = response;
    throw error;
}

function business(response) {
    if (response.head && response.head.code === 0) {
        throw response.head.msg;
    } else {
        return response;
    }
}


function checkDataSta(data){
    if(data.sta === 99997){
        iView.Message.error(data.msg);
        const error = new Error(data.msg);
        error.data = data;
        let login = { name: 'login', params: { returl: router.history.current.path }};
        router.push(login);
        throw error;
    }
    // else if(data.sta === 308){
    //     iView.Message.error(data.msg);
    //     const error = new Error(data.msg);
    //     error.data = data;
    //     let login = { name: 'login', params: { returl: router.history.current.path }};
    //     router.push(login);
    //     throw error;
    // }
    else if(data.sta === 99998||data.sta === 99999||data.sta === 99996){
        iView.Message.error(data.msg);
        const error = new Error(data.msg);
        error.data = data;
        throw error;
    }
    return data;
}

function checkThisPageElements(res){
  if (res.data && res.data.thisPageElements !== undefined && res.data.thisPageElements === null){
    res.data.thisPageElements = new Array();
  }
  return res;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options = {}) {

    return fetch(config.API_HOST+url, options)
        .then(checkStatus)
        .then(parseJSON)
        .then(business)
        .then(checkDataSta)
        .then(checkThisPageElements)
        .then(data => ({ data }));
}

export function post(url, data) {
    return request(url, {
        method: 'POST',
        credentials:"include",
        body:parseFormData(data || {})
    })
}

export function jsonp(url){
  return fetchJsonp(url)
      .then(response => response.json());
}

export function download(url, data = {}){
  let keys = Object.keys(data);
  let args = '';
  keys.forEach((key,i) => {
    if (data[key] !== undefined && data[key] !== null && data[key] !== ''){
      args += `${key}=${data[key]}&`;
    }
  });
  if (args.length > 0) args = args.substring(0,args.length-1);
  let uri = config.API_HOST + url + '?' + args;
  window.location.href = encodeURI(uri);
}
